#include "layer.hpp"

#include <spdlog/spdlog.h>
#include "../ecs/ecs.hpp"
#include "../ui_message/message.h"

#include "../layout/layout.hpp"

namespace qbe::layer {

void update(ecs::Query query, ecs::Bus& bus) {
  auto& model = query.get_resource<layer::Model>();

  auto lib_msg = bus.receive<UiMessage::GetLibLayerMap>();
  auto new_msg = bus.receive<UiMessage::CreateNewLayer>();
  auto edit_msg = bus.receive<UiMessage::EditLayer>();
  auto edit_num_msg = bus.receive<UiMessage::EditLayerNumber>();
  auto delete_msg = bus.receive<UiMessage::DeleteLayer>();
  auto merge_msg = bus.receive<UiMessage::MergeLayer>();
  auto clear_msg = bus.receive<UiMessage::ClearLayer>();

  auto& event_writer = query.get_event_writer<Event>();

  auto& load_event_writer = query.get_event_writer<LoadEvent>();
  auto& add_event_writer = query.get_event_writer<AddEvent>();
  auto& remove_event_writer = query.get_event_writer<RemoveEvent>();
  auto& edit_event_writer = query.get_event_writer<EditEvent>();

  if (!lib_msg.empty()) {
    SPDLOG_INFO("[layer] lib ");
    auto lib = lib_msg.back();
    for (auto& [num, info] : lib.libLayerMap) {
      model.add(info);
    }

    load_event_writer.send({{}});
    // event_writer.send({{Code::Load}});
    // SPDLOG_INFO("[layer] num: {}", num);
  }
  if (!new_msg.empty()) {
    SPDLOG_INFO("[layer] new ");
    auto d = edit_msg.back();
    model.add(d.layer);
    qlib::Tag tag{d.layer.layer_number, 0};
    add_event_writer.send({{tag}});
  }
  if (!edit_msg.empty()) {
    SPDLOG_INFO("[layer] edit ");
    auto d = edit_msg.back();
    model.edit(edit_msg.back().layer);
    qlib::Tag tag{d.layer.layer_number, 0};
    // event_writer.send({{Code::Edit}});
    edit_event_writer.send({{tag}});
  }
  if (!edit_num_msg.empty()) {
    SPDLOG_INFO("[layer] edit num");
  }
  if (!delete_msg.empty()) {
    SPDLOG_INFO("[layer] delete ");
    auto d = delete_msg.back();
    for (auto n : d.delete_layer_numbers) {
      qlib::Tag tag{n, 0};
      model.remove(tag);
      // event_writer.send({{Code::Remove}});
      remove_event_writer.send({{tag}});
    }
  }
  if (!merge_msg.empty()) {
    SPDLOG_INFO("[layer] merge");
  }
  if (!clear_msg.empty()) {
    SPDLOG_INFO("[layer] clear");
  }
}

void clear_event(ecs::Query query) {
  query.get_resource<ecs::Event<Event>>().clear();
  query.get_resource<ecs::Event<LoadEvent>>().clear();
  query.get_resource<ecs::Event<AddEvent>>().clear();
  query.get_resource<ecs::Event<RemoveEvent>>().clear();
  query.get_resource<ecs::Event<EditEvent>>().clear();
}

void LayerPlugin::build(ecs::App& app) {
  app.insert_resource<Manager>(Manager());
  app.insert_resource<Model>(Model());
  // app.init_event<Event>();

  // app.init_event<LoadEvent>();
  // app.init_event<AddEvent>();
  // app.init_event<RemoveEvent>();
  // app.init_event<EditEvent>();

  // app.add_systems<ecs::stage::PreUpdate>(update);
  // app.add_systems<ecs::stage::Last>(clear_event);
}

}  // namespace qbe::layer